package org.alfresco.crowd;

import org.acegisecurity.providers.AbstractAuthenticationToken;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.alfresco.repo.admin.patch.PatchExecuter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.atlassian.crowd.integration.acegi.CrowdAuthenticationProvider;

import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.providers.AuthenticationProvider;

public class EncapsulatingCrowdAuthenticationProvider implements
		AuthenticationProvider {

	private static Log logger = LogFactory.getLog(EncapsulatingCrowdAuthenticationProvider.class);

	private CrowdAuthenticationProvider provider;

	public EncapsulatingCrowdAuthenticationProvider() {
		super();
		logger.info("Initializing EncapsulatingCrowdAuthenticationProvider");
	}

	public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
		logger.debug("Calling EncapsulatingCrowdAuthenticationProvider.authenticate");
    	UsernamePasswordAuthenticationToken localAuth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials());

    	org.acegisecurity.Authentication result;
		try{
        	result = provider.authenticate(localAuth);
    		logger.debug("Success");
    	}catch (org.acegisecurity.AuthenticationException e){
    		logger.debug("Failure authenticating",e);
    		throw new net.sf.acegisecurity.BadCredentialsException(e.toString());
    	}

		authentication.setAuthenticated(result.isAuthenticated());
		return authentication;
    }

	public boolean supports(Class authentication) {
		return true; //provider.supports(authentication);
	}

	public void setEncapsulatedProvider(
			CrowdAuthenticationProvider encapsulatedProvider) {
		this.provider = encapsulatedProvider;
	}

}
